package cn.wolfcode.job;

import cn.wolfcode.common.web.Result;
import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.feign.SeckillProductFeignApi;
import cn.wolfcode.redis.JobRedisKey;
import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Getter
@Setter
public class MyInitSeckillProductJob implements SimpleJob {
    @Value("${jobCron.initSeckillProduct}")
    private String cron;

    @Autowired
    private SeckillProductFeignApi seckillProductFeignApi;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void execute(ShardingContext shardingContext) {
        System.out.println(shardingContext.getShardingParameter());
        //携带分片参数
        doWork(shardingContext.getShardingParameter());
    }

    private void doWork(String time) {
        //远程调用秒杀服务把数据查询出来  Result  data：List<SeckillProductVO>
        Result<List<SeckillProductVo>> result = seckillProductFeignApi.selectByTime(Integer.parseInt(time));
        /**
         * result 数据一共有集几种情况
         * 1 秒杀服务直接挂掉，走降级的方法返回值是null
         * 2 服务调用没问题  返回 {code:200,msg:操作成功,data:List<SeckillProductVo>}
         * 3 秒杀服务内部出现问题  {code:502xx,msg:"服务繁忙"}
         */
        if (result != null && !result.hasError()){ //第二种情况
            List<SeckillProductVo> seckillProductVos = result.getData();
            if (seckillProductVos != null && seckillProductVos.size() > 0){ //如果有数据
                //把查询出来的数据放到redis中
                for (SeckillProductVo seckillProductVo : seckillProductVos) {
                    redisTemplate.opsForHash().put(JobRedisKey.SECKILL_PRODUCT_LIST.getRealKey(time),
                            seckillProductVo.getId()+"", JSON.toJSONString(seckillProductVo));

                    redisTemplate.opsForHash().put(JobRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(time),
                            seckillProductVo.getId()+"",seckillProductVo.getStockCount()+"");
                }
                System.out.println("数据同步成功"+time);
            }
        }
    }
}
